# -*- coding: utf-8 -*-

from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from app.lib.email_runner.abstract_email import AbstractEmail


class EmailFile(AbstractEmail):
    """
    发送附件邮件
    """

    def __init__(self, subject="", msg_from="", msg_to=""):
        super().__init__(subject, msg_from, msg_to)

    def set_message(self, msg, msg_type="plain"):
        """
        设置消息
        :param msg: string 消息内容
        :param msg_type: string 消息类型
        """

        message = MIMEMultipart()
        message['From'] = Header(self._msg_from, 'utf-8')  # 发送者
        message['To'] = Header(self._msg_to, 'utf-8')  # 接收者
        message['Subject'] = Header(self._msg_subject, 'utf-8')  # 邮件标题

        # 邮件正文内容
        message.attach(MIMEText(msg, msg_type, 'utf-8'))

        self.message = message

    def attach_file(self, filepath, filename):
        """
        添加附件
        :param filepath: string 文件路径
        :param filename: string 文件名称
        """

        with open(filepath, "rb") as r:
            content = r.read()

        file = MIMEText(content, 'base64', 'utf-8')

        file["Content-Type"] = 'application/octet-stream'
        file["Content-Disposition"] = 'attachment; filename="{filename}"'.format(filename=filename)

        self.message.attach(file)
